﻿using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using SilverlightApplication1.Interfaces;

namespace SilverlightApplication1.Controls
{
    public partial class GalleryControl : AnimatedControl
    {        
        public GalleryControl()
        {
            InitializeComponent();
            Loaded += GalleryControl_Loaded;
        }

        public void ImagesListSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (imagesList != null)
            {
                selectedImg.DataContext = imagesList.SelectedItem;
            }
        }

        public override void RunAnimation()
        {
            var gallery = new Gallery
                              {
                                  ImagesModels = imagesList.Items,
                                  SelectedImg = selectedImg
                              };
            ThreadPool.QueueUserWorkItem(SlideShow, gallery);
        }

        private void SlideShow(Object gallery)
        {
            ItemCollection imagesModels = ((Gallery) gallery).ImagesModels;

            foreach (var imageModel in imagesModels)
            {
                var model = imageModel;
                Dispatcher.BeginInvoke(() => { selectedImg.DataContext = model; });
                Thread.Sleep(SlideShowTimeout);
            }

            Dispatcher.BeginInvoke(InvokeAnimationCompleted);
        }

        private void GalleryControl_Loaded(Object sender, RoutedEventArgs e)
        {
            if (imagesList.Items != null && imagesList.Items.Count > 0)
            {
                selectedImg.DataContext = imagesList.Items[0];
            }
        }

        #region Nested type: Gallery

        private class Gallery
        {
            public ItemCollection ImagesModels;
            public Image SelectedImg;
        }

        #endregion

        private const int SlideShowTimeout = 1000;
    }
}